<template>
  <div class="file-management-container">
    <div class="header-actions">
      <el-button type="primary" @click="handleUploadClick">
        <el-icon-plus /> 上传文件
      </el-button>
    </div>

    <el-table :data="fileList" style="width: 100%">
      <el-table-column label="预览" width="60">
        <template #default="scope">
          <!-- 为图片添加点击事件 -->
          <el-image
            v-if="isImageFile(scope.row)"
            :src="getPreviewUrl(scope.row)"
            style="width: 40px; height: 40px; cursor: pointer"
            fit="cover"
            alt="图片预览"
            @click="handlePreview(scope.row)"
          />
          <!-- 非图片文件显示文件夹图标 -->
          <el-icon v-else style="width: 24px; height: 24px; color: #409EFF;">
            <Folder />
          </el-icon>
        </template>
      </el-table-column>
      <el-table-column prop="fileName" label="文件名" width="250" />
      <el-table-column prop="fileSize" label="大小(KB)" width="100" />
      <el-table-column prop="fileType" label="类型" width="100" />
      <el-table-column prop="uploadTime" label="上传时间" width="180" />
      <el-table-column prop="downloadUrl" label="操作" width="240">
        <template #default="scope">
          <!-- 添加图片预览按钮 -->
          <el-button 
            v-if="isImageFile(scope.row)"
            type="text"
            icon="el-icon-view"
            @click="handlePreview(scope.row)"
          >预览</el-button>
          <el-button type="text" danger @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :current-page="currentPage"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <el-dialog v-model="uploadDialogVisible" title="上传文件">
      <el-upload
        class="upload-demo"
        action="/blog-admin/storage/files/upload"
        :on-success="handleUploadSuccess"
        :file-list="uploadFileList"
        :auto-upload="true"
        :headers="getHeaders()"
      >
        <el-button type="primary">选择文件</el-button>
        <template #tip>
          <div class="el-upload__tip">
            支持 JPG、PNG、PDF 等格式，单个文件不超过 10MB
          </div>
        </template>
      </el-upload>
    </el-dialog>

    <!-- 图片预览对话框 -->
    <el-dialog v-model="previewDialogVisible" title="图片预览" width="80%">
      <el-image
        :src="previewImageUrl"
        fit="contain"
        style="width: 100%; height: 80vh;"
      ></el-image>
    </el-dialog>
  </div>
</template>

<script setup>
// 仅保留文件夹图标导入
import { Folder } from '@element-plus/icons-vue'
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { fileApi } from '@/api/fileApi'

const getHeaders = () => ({
  Authorization: `Bearer ${localStorage.getItem('token') || ''}`
})

// 状态管理
const fileList = ref([])
const uploadDialogVisible = ref(false)
const uploadFileList = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchFileList()
}
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchFileList()
}

// 生命周期
onMounted(() => {
  fetchFileList()
})

// 方法
const fetchFileList = async () => {
  try {
    const response = await fileApi.getFileList(currentPage.value, pageSize.value)
    
    fileList.value = response.data.content
    total.value = response.data.totalElements
  } catch (error) {
    ElMessage.error('获取文件列表失败: ' + (error.message || '未知错误'))
  }
}

const handleUploadClick = () => {
  uploadDialogVisible.value = true
}

const handleUploadSuccess = () => {
  ElMessage.success('文件上传成功')
  uploadDialogVisible.value = false
  fetchFileList() // 重新获取文件列表
  uploadFileList.value = []
}



const handleDelete = async (file) => {
  try {
    await fileApi.deleteFile(file.id)
    ElMessage.success('文件删除成功')
    fetchFileList() // 重新获取文件列表
  } catch (error) {
    ElMessage.error('文件删除失败: ' + (error.message || '未知错误'))
  }
}

// 添加预览相关状态
const previewDialogVisible = ref(false)
const previewImageUrl = ref('')

// 修改图片判断逻辑，使用fileType字段
const isImageFile = (file) => {
  // 检查fileType是否以image/开头
  return file?.fileType?.startsWith('image/') || false;
}

// 修改预览处理函数参数
// 统一图片URL生成方法
const getPreviewUrl = (file) => {
  if (!file?.filePath) return '';
  const normalizedPath = file.filePath.replace(/^\//, '');
  return `/api/${normalizedPath}`;
}

// 修改handlePreview方法以使用统一的URL生成
const handlePreview = (file) => {
  if (!file?.filePath) {
    ElMessage.error('文件路径不存在');
    return;
  }
  previewImageUrl.value = getPreviewUrl(file);
  previewDialogVisible.value = true;
}
</script>

<style scoped>
.header-actions {
  margin-bottom: 16px;
  display: flex;
  justify-content: flex-end;
}
</style>